<?php

namespace app\adminapi\controller;

use app\model\DictModel;
use app\model\DictTypeModel;
use Respect\Validation\Exceptions\ValidationException;
use Respect\Validation\Validator as v;
use Webman\Http\Request;

class Dict extends BaseAdminApi
{
    protected $dataModel = DictModel::class;
    protected array $allowSearch = ['dict_label', 'dict_value', 'dict_type', 'status'];

    /**
     * 获取字典类型列表
     */
    public function getDictTypes(Request $request)
    {
        try {
            $params = v::input($request->get(), [
                'pageSize' => v::optional(v::intVal()->min(1)->max(100))->setName('分页大小'),
                'dict_name' => v::optional(v::stringType())->setName('字典名称'),
                'dict_type' => v::optional(v::stringType())->setName('字典类型'),
                'status' => v::optional(v::intVal()->in([0,1]))->setName('状态'),
            ]);
        } catch (ValidationException $e) {
            return $this->fail($e->getMessage());
        }

        $pageSize = $params['pageSize'] ?? 10;

        $query = DictTypeModel::query();

        // 搜索条件
        if (!empty($params['dict_name'])) {
            $query->where('dict_name', 'like', '%' . $params['dict_name'] . '%');
        }
        if (!empty($params['dict_type'])) {
            $query->where('dict_type', 'like', '%' . $params['dict_type'] . '%');
        }
        if (isset($params['status'])) {
            $query->where('status', $params['status']);
        }

        $paginate = $query->orderBy('created_at', 'desc')
            ->paginate($pageSize);

        return $this->dataByPage($paginate);
    }

    /**
     * 保存字典类型
     */
    public function saveDictType(Request $request)
    {
        try {
            $params = v::input($request->post(), [
                'id' => v::optional(v::stringType()->notEmpty())->setName('字典类型ID'),
                'dict_name' => v::stringType()->notEmpty()->length(1, 100)->setName('字典名称'),
                'dict_type' => v::stringType()->notEmpty()->length(1, 100)->regex('/^[a-zA-Z0-9_]+$/')->setName('字典类型'),
                'status' => v::intVal()->in([0,1])->setName('状态'),
                'remark' => v::optional(v::stringType()->length(0, 500))->setName('备注'),
            ]);
        } catch (ValidationException $e) {
            return $this->fail($e->getMessage());
        }

        try {
            if (isset($params['id']) && !empty($params['id'])) {
                // 编辑字典类型
                $dictType = DictTypeModel::find($params['id']);
                if (!$dictType) {
                    return $this->fail('字典类型不存在');
                }

                // 检查字典类型是否重复（排除自己）
                $existDictType = DictTypeModel::where('dict_type', $params['dict_type'])
                    ->where('id', '!=', $params['id'])
                    ->first();
                if ($existDictType) {
                    return $this->fail('字典类型已存在');
                }

                $dictType->update($params);
                $message = '字典类型更新成功';
            } else {
                // 新增字典类型
                $existDictType = DictTypeModel::where('dict_type', $params['dict_type'])->first();
                if ($existDictType) {
                    return $this->fail('字典类型已存在');
                }

                DictTypeModel::create($params);
                $message = '字典类型创建成功';
            }

            return $this->success($message);
        } catch (\Exception $e) {
            return $this->fail('操作失败：' . $e->getMessage());
        }
    }

    /**
     * 删除字典类型
     */
    public function deleteDictType(Request $request)
    {
        try {
            $params = v::input($request->post(), [
                'id' => v::stringType()->notEmpty()->setName('字典类型ID'),
            ]);
        } catch (ValidationException $e) {
            return $this->fail($e->getMessage());
        }

        try {
            $dictType = DictTypeModel::find($params['id']);
            if (!$dictType) {
                return $this->fail('字典类型不存在');
            }

            // 检查是否有字典数据
            $hasData = DictModel::where('dict_type', $dictType->dict_type)->exists();
            if ($hasData) {
                return $this->fail('该字典类型下存在字典数据，请先删除字典数据');
            }

            $dictType->delete();

            return $this->success('字典类型删除成功');
        } catch (\Exception $e) {
            return $this->fail('删除失败：' . $e->getMessage());
        }
    }

    /**
     * 保存字典数据
     */
    public function saveDictData(Request $request)
    {
        try {
            $params = v::input($request->post(), [
                'id' => v::optional(v::stringType()->notEmpty())->setName('字典数据ID'),
                'dict_type' => v::stringType()->notEmpty()->length(1, 100)->setName('字典类型'),
                'dict_label' => v::stringType()->notEmpty()->length(1, 100)->setName('字典标签'),
                'dict_value' => v::stringType()->notEmpty()->length(1, 100)->setName('字典键值'),
                'dict_sort' => v::optional(v::intVal()->min(0))->setName('显示顺序'),
                'css_class' => v::optional(v::stringType()->length(0, 100))->setName('样式属性'),
                'list_class' => v::optional(v::stringType()->length(0, 100))->setName('表格回显样式'),
                'is_default' => v::intVal()->in([0,1])->setName('是否默认'),
                'status' => v::intVal()->in([0,1])->setName('状态'),
                'remark' => v::optional(v::stringType()->length(0, 500))->setName('备注'),
            ]);
        } catch (ValidationException $e) {
            return $this->fail($e->getMessage());
        }

        // 设置默认排序
        if (!isset($params['dict_sort']) || $params['dict_sort'] === '') {
            $params['dict_sort'] = 0;
        }

        try {
            // 检查字典类型是否存在
            $dictTypeExists = DictTypeModel::where('dict_type', $params['dict_type'])->exists();
            if (!$dictTypeExists) {
                return $this->fail('字典类型不存在');
            }

            if (isset($params['id']) && !empty($params['id'])) {
                // 编辑字典数据
                $dictData = DictModel::find($params['id']);
                if (!$dictData) {
                    return $this->fail('字典数据不存在');
                }

                // 检查同一字典类型下字典值是否重复（排除自己）
                $existDictData = DictModel::where('dict_type', $params['dict_type'])
                    ->where('dict_value', $params['dict_value'])
                    ->where('id', '!=', $params['id'])
                    ->first();
                if ($existDictData) {
                    return $this->fail('该字典类型下字典键值已存在');
                }

                $dictData->update($params);
                $message = '字典数据更新成功';
            } else {
                // 新增字典数据
                $existDictData = DictModel::where('dict_type', $params['dict_type'])
                    ->where('dict_value', $params['dict_value'])
                    ->first();
                if ($existDictData) {
                    return $this->fail('该字典类型下字典键值已存在');
                }

                DictModel::create($params);
                $message = '字典数据创建成功';
            }

            return $this->success($message);
        } catch (\Exception $e) {
            return $this->fail('操作失败：' . $e->getMessage());
        }
    }

    /**
     * 删除字典数据
     */
    public function deleteDictData(Request $request)
    {
        try {
            $params = v::input($request->post(), [
                'id' => v::stringType()->notEmpty()->setName('字典数据ID'),
            ]);
        } catch (ValidationException $e) {
            return $this->fail($e->getMessage());
        }

        try {
            $dictData = DictModel::find($params['id']);
            if (!$dictData) {
                return $this->fail('字典数据不存在');
            }

            $dictData->delete();

            return $this->success('字典数据删除成功');
        } catch (\Exception $e) {
            return $this->fail('删除失败：' . $e->getMessage());
        }
    }

    /**
     * 获取所有字典类型（用于下拉选择）
     */
    public function getAllDictTypes(Request $request)
    {
        $dictTypes = DictTypeModel::where('status', 1)
            ->orderBy('created_at', 'desc')
            ->get(['id', 'dict_name', 'dict_type']);

        return $this->success($dictTypes);
    }

    /**
     * 根据字典类型获取字典数据（用于前端选择）
     */
    public function getDictDataByType(Request $request)
    {
        $params = $request->get();
        
        if (empty($params['dict_type'])) {
            return $this->fail('字典类型不能为空');
        }

        $dictData = DictModel::where('dict_type', $params['dict_type'])
            ->where('status', 1)
            ->orderBy('dict_sort', 'asc')
            ->orderBy('created_at', 'desc')
            ->get(['dict_label', 'dict_value', 'css_class', 'list_class']);

        return $this->success($dictData);
    }
}